<template>
	<view class="div">
		<nav-bar :title="id" leftIcon="left"></nav-bar>
		<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scroll="scroll">
			<view v-for="item in  messageList " :key="item">
				<view v-if="item.messageType == 1" class="itemleft">
					<image src="@/static/user.png" class="img" />
					<view class="text">
						<view style="color: #fff;margin-bottom: 10rpx;">
							<!-- {{ id margin-left: 20rpx; }} -->
							<text style="font-size: 22rpx;">
								{{ item.createTimeStr }}</text>
						</view>
						<view style="color: #fff;word-wrap: break-word;">{{ item.messageText }}</view>
						<view v-if="item.picOne != null">
							<image :src="item.picOne" class="imgItem" v-if="item.picOne" @click="previewImg(item.picOne)">
							</image>
							<image :src="item.picTwo" class="imgItem" v-if="item.picTwo" @click="previewImg(item.picTwo)">
							</image>
							<image :src="item.picThree" class="imgItem" v-if="item.picThree"
								@click="previewImg(item.picThree)">
							</image>
							<image :src="item.picFour" class="imgItem" v-if="item.picFour"
								@click="previewImg(item.picFour)">
							</image>
							<image :src="item.picFive" class="imgItem" v-if="item.picFive"
								@click="previewImg(item.picFive)">
							</image>
							<image :src="item.picSix" class="imgItem" v-if="item.picSix" @click="previewImg(item.picSix)">
							</image>
						</view>
					</view>
				</view>
				<view v-if="item.messageType == 2" class="itemright">
					<view class="text">
						<view style="color: #fff;display: flex;justify-content: flex-end;margin-bottom: 10rpx;">
							<text style="font-size: 22rpx;">
								{{ item.createTimeStr }}</text>
							<!-- 客服 margin-right: 20rpx; -->
						</view>
						<view style="color: #fff;word-wrap: break-word;float: right;">{{ item.messageText }}
						</view>
					</view>
					<image src="@/static/user.png" class="img" />
				</view>
			</view>
		</scroll-view>
		<view class="ipt">
			<uni-easyinput :placeholder="$t('請輸入需要發送的消息')" @keydown.enter.prevent="send" class="uni-mt-5"
				v-model="text"></uni-easyinput>
			<!-- 			<uni-file-picker class="upload" v-model="imgfileList" file-mediatype="image" @select="select" limit="1"
				style="color: #999;"></uni-file-picker> -->
			<button type="primary" @click="send" class="btn">{{ $t('發送') }}</button>
		</view>
	</view>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { onLoad, onShow, onUnload, onHide } from "@dcloudio/uni-app";
import { axios, socketUrl, axiosLogin } from '@/service/request.js'
import { getCurrentFormattedTime } from "../../utils/check";
import i18n from '@/locale/index'

const scrollTop = ref(0)
const id = ref('')
const text = ref('')
const SocketTask = ref(null)
const isOpenSocket = ref(false)
const imgfileList = ref([])//https://th.bing.com/th/id/OIP.u1D8WJbUIIXMV2w-qa4r5wAAAA?w=197&h=197&c=7&r=0&o=5&pid=1.7
const messageList = ref([])
const heightbom = ref(999999999)

const errNum = ref(0)


onLoad((res) => {
	id.value = res.id
})

onShow(async () => {
	//告诉服务器客服正在和谁对话
	await axiosLogin('messageBoard/getLockUserId', {
		userId: id.value,
		serviceId: uni.getStorageSync("setUserInfo").userId,
		type: 2   //(1、用户、2、客服)
	})
	getList()
	if (time) {
		clearInterval(time)
	}
	initSocket()
})
onMounted(() => {
	// initSocket()
	//#ifdef H5
	window.scrollTo(0, document.body.scrollHeight);
	//#endif
	// const height = document.querySelector('.uni-scroll-view-content')
	heightbom.value = heightbom.value + 100000
	scrollTop.value = heightbom.value
})

//获取聊天列表
const getList = async (e) => {
	console.log('获取用户列表!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
	const data = await axios('messageBoard/queryMessageBoard', {
		userId: id.value
	})
	messageList.value = data
	nextTick(() => {
		// const height = document.querySelector('.uni-scroll-view-content')
		heightbom.value = heightbom.value + 100000
		scrollTop.value = heightbom.value
	})
}

function scroll(params) {

}

let time
//初始化socket
function initSocket() {
	SocketTask.value = uni.connectSocket({
		url: socketUrl + `${uni.getStorageSync("setUserInfo").userId}` + `/2/${id.value}`,
		// header: {
		// 	'content-type': 'application/json'
		// },
		// protocols: ['protocol1'],
		// method: 'GET'，
		success(data) {
		},
	});
	// 监听WebSocket连接打开事件
	SocketTask.value.onOpen((data) => {
		isOpenSocket.value = true

		// 注：只有连接正常打开中 ，才能正常收到消息
		if (isOpenSocket.value) {
			SocketTask.value.onMessage((res) => {
				errNum.value = 0
				console.log('收到服务器内容!!!!!!!!!：');
				console.log(res);
				if (res.data === '连接成功') {
					return
				}
				const data = JSON.parse(res.data)
				switch (data.contentType) {
					// case 1:
					// 	messageList.value = data.boardList
					// 	break;
					case 2:
						messageList.value.push({
							messageText: data.messageText,
							messageType: 1,
							createTimeStr: getCurrentFormattedTime(),
							picOne: data.picList[0],
							picTwo: data.picList[1],
							picThree: data.picList[2],
							picFour: data.picList[3],
							picFive: data.picList[4],
							picSix: data.picList[5],
						})
						break;
				}
				nextTick(() => {
					// uni.pageScrollTo({
					// 	scrollTop: document.body.scrollHeight,  // 一个足够大的值以确保滚动到底部
					// 	duration: 0,   // 滚动的持续时间，单位为毫秒
					// });
					//#ifdef H5
					window.scrollTo(0, document.body.scrollHeight);
					//#endif
					// const height = document.querySelector('.uni-scroll-view-content')
					heightbom.value = heightbom.value + 100000
					scrollTop.value = heightbom.value
				})
			});
		} else {
			uni.showToast({
				title: `WebSocket ERROR !`,
				icon: 'error',
			})
		}
	})
	//监听 WebSocket 错误事件
	SocketTask.value.onError((errMsg) => {
		console.log(errMsg);
		console.log('WebSocket连接打开失败，请检查！!!!!!!!!!!!!!!');
		if (time) {
			clearInterval(time)
		}
		if (errNum.value >= 4) {
			console.log('刷新了！！！！！！！！！', 'pages\Customer\Customer.vue-第424行')
			return uni.redirectTo({
				url: `/pages/chat/chat?id=${id.value}`
			})
		}
		time = setTimeout(() => {
			initSocket()
			errNum.value++
			getList()
		}, 1000)
	})

	// 这里仅是事件监听【如果socket关闭了会执行】
	SocketTask.value.onClose((code) => {
		isOpenSocket.value = false;
		// uni.showToast({
		// 	title: `${i18n.global.t('連接已斷開,請刷新頁面')}!`,
		// 	icon: 'error',
		// })
		if (code.code == 1000) {
			return
		}
		if (time) {
			clearInterval(time)
		}
		if (errNum.value >= 4) {
			return uni.redirectTo({
				url: `/pages/chat/chat?id=${id.value}`
			})
		}
		time = setTimeout(() => {
			initSocket()
			errNum.value++
			getList()
		}, 1000)

	});

}

// 关闭websocket【离开这个页面的时候执行关闭】
function closeSocket() {
	SocketTask.value.close({
		success(res) {
			isOpenSocket.value = false;
		},
		fail(err) {
		},
	});
}

onUnload(() => {
	if (time) {
		clearInterval(time)
	}
	closeSocket()
})
onHide(() => {
	if (time) {
		clearInterval(time)
	}
	closeSocket()
})


//发送聊天内容
function send() {
	if (text.value == '') {
		return uni.showToast({
			title: `${i18n.global.t('消息不能為空')}!`,
			icon: 'none',
		})
	}
	if (!isOpenSocket.value) {
		return uni.showToast({
			title: `${i18n.global.t('連接已斷開,請刷新頁面')}!`,
			icon: 'error',
		})
	}

	// 注：只有连接正常打开中 ，才能正常成功发送消息
	SocketTask.value.send({
		data: JSON.stringify({
			msg: text.value,
			type: 2, //1:用户 2:客服    当前用户的类型
			userId: uni.getStorageSync("setUserInfo").userId,  //自己的id
			consumerId: id.value //对方的id
		}),
		async success(data) {
			messageList.value.push({
				messageText: text.value,
				messageType: 2,
				createTimeStr: getCurrentFormattedTime(),
			})
			nextTick(() => {
				//#ifdef H5
				window.scrollTo(0, document.body.scrollHeight);
				//#endif
				// const height = document.querySelector('.uni-scroll-view-content')
				heightbom.value = heightbom.value + 100000
				scrollTop.value = heightbom.value
			})
			text.value = ''
		},
		fail(err) {
			uni.showToast({
				title: `发送失败`,
				icon: 'error',
			})
		},
	});

}

//上传图片
function select(e) {
}

//预览图片
function previewImg(photoImg) {
	let imgsArray = [];
	imgsArray[0] = photoImg;
	uni.previewImage({
		current: 0,
		urls: imgsArray
	});
}
</script>

<style lang="scss">
.scroll-Y {
	width: 690rpx;
	// height: calc(100vh - 150rpx - 100rpx);
	max-height: 80vh;
	padding: 0 30rpx 100rpx 30rpx;

	.itemleft {
		display: flex;
		justify-content: flex-start;
		// align-items: center;
		width: calc(100vw - 60rpx);
		min-height: 100rpx;
		background-color: #081C26;
		// border-radius: 50rpx;
		// margin-bottom: 20rpx;
		padding: 15rpx 100rpx 15rpx 0;

		.text {
			width: calc(100vw - 60rpx - 220rpx);
		}

		.img {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
		}

		.imgItem {
			width: 100rpx;
			height: 100rpx;
			margin-right: 15rpx;
		}
	}

	.itemright {
		display: flex;
		// align-items: center;
		justify-content: flex-end;
		width: calc(100vw - 60rpx);
		min-height: 100rpx;
		background-color: #081C26;
		// border-radius: 50rpx;
		// margin-bottom: 20rpx;
		padding: 15rpx 0 15rpx 0;


		.text {
			max-width: calc(100vw - 60rpx - 220rpx);
		}

		.img {
			max-width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
		}
	}
}

.ipt {
	// display: flex;
	// align-items: center;
	// justify-content: space-between;
	height: 80rpx;
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;

	.uni-mt-5 {
		width: 530rpx;
		// width: 690rpx;
		height: 100%;
		padding: 0 30rpx;

		.uni-easyinput__content {
			height: 100%;

		}
	}

	.upload {
		position: absolute;
		top: -84rpx;
		right: -380rpx;
		display: inline;
		transform: scale(0.3);
	}

	.btn {
		position: absolute;
		top: 2rpx;
		right: 30rpx;
		width: 150rpx;
		height: 70rpx;
		font-size: 28rpx;
	}



}
</style>